<?php
namespace WebApper\Shortcode;

/*
 * [paymentmethods]
 *
 */
 class PaymentMethods extends \WebApper\Shortcode {
	
    /**
     * Define shortcode properties
     *
     */
	protected $shortcode = 'payment_methods';

    /**
     * Initialize the Shortcode Class
     *
     */
    public function __construct() {
		add_shortcode( $this->shortcode, array($this, 'shortcode') );
		add_action( 'wp_ajax_web_apper' . $this->shortcode, array($this, 'sendAjaxResponse') );
		add_action( 'wp_ajax_nopriv_web_apper' . $this->shortcode, array($this, 'sendAjaxResponse') );	   	
	}

    /**
     * Handles the add post shortcode
     *
     * @param array $atts
     */
	 
    public function shortcode( $atts ) {

	global $wpdb, $webapper;
	$post_id = $_GET['postID'];  // Get the post ID
	$name_on_card = trim($_POST['name_on_card']);
	$credit_card_type = trim($_POST['credit_card_type']);	
	$card_number = base64_encode(trim($_POST['card_number']));	
	$cardExpirationMonth = trim($_POST['cardExpirationMonth']);	
	$cardExpirationYear = trim($_POST['cardExpirationYear']);
	$card_country = trim($_POST['card_country']);	
	$card_address = trim($_POST['card_address']);
	$card_city = trim($_POST['card_city']);	
	$card_state = trim($_POST['card_state']);
	$card_ccv = base64_encode(trim($_POST['card_ccv']));
	$card_billing_zip = trim($_POST['card_billing_zip']);	
	$bank_routing_number = base64_encode(trim($_POST['bank_routing_number']));
	$bank_account_number = base64_encode(trim($_POST['bank_account_number']));	
	$bank_check_number = base64_encode(trim($_POST['bank_check_number']));
	$user_payment_master_id = $_POST['hidden_payment_master_id'];
	
	$get_post_meta      = get_post_meta($post_id);
	$email_address 		= $get_post_meta['email-primary'][0];
	$exist_user_id = email_exists($email_address);
	if($exist_user_id !=''){  // This Lead is an user
		// Save Payment information
		if (isset($_POST['saveCardInfo'])){ 
		
			if($_POST['hidden_payment_master_id']==''){ // payment information exist for this user
				// Insert
				$result = $wpdb->insert( 
					$webapper->tables->user_payment_master, 
					array( 
					 'user_id'        			=> $exist_user_id,
					 'card_holder_name' 		=> $name_on_card,
					 'card_type'				=> $credit_card_type,
					 'card_number' 				=> $card_number,
					 'card_expiration_month' 	=> $cardExpirationMonth,
					 'card_expiration_year' 	=> $cardExpirationYear,
					 'card_country' 			=> $card_country,
					 'card_address' 			=> $card_address,
					 'card_city' 				=> $card_city,
					 'card_state' 				=> $card_state,
					 'card_ccv' 				=> $card_ccv,
					 'card_zip_code' 			=> $card_billing_zip,
					 'bank_routing_number' 		=> $bank_routing_number,
					 'bank_account_number' 		=> $bank_account_number,
					 'bank_check_number' 		=> $bank_check_number,	
					), 
					array( '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s','%s', '%s', '%s', '%s', '%s', '%s')
				);
				$this->user_payment_master_id = $wpdb->insert_id;
			 }
				else{
				// Update 
			    $result = $wpdb->update( 
				$webapper->tables->user_payment_master, 
				array( 
					 'user_id'        			=> $exist_user_id,
					 'card_holder_name' 		=> $name_on_card,
					 'card_type'				=> $credit_card_type,
					 'card_number' 				=> $card_number,
					 'card_expiration_month' 	=> $cardExpirationMonth,
					 'card_expiration_year' 	=> $cardExpirationYear,
					 'card_country' 			=> $card_country,
					 'card_address' 			=> $card_address,
					 'card_city' 				=> $card_city,
					 'card_state' 				=> $card_state,
					 'card_ccv' 				=> $card_ccv,
					 'card_zip_code' 			=> $card_billing_zip,
					 'bank_routing_number' 		=> $bank_routing_number,
					 'bank_account_number' 		=> $bank_account_number,
					 'bank_check_number' 		=> $bank_check_number,
					
				), 
				array( 'user_payment_master_id' =>  $user_payment_master_id ), 
				array( '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s','%s', '%s', '%s', '%s', '%s', '%s'), 
				array( '%d' ) 
			);	
				
			       }
			
		}
	}
	else {
		$first_name = $get_post_meta['first-name'][0]; 
		$last_name = $get_post_meta['last-name'][0];
		$user_pass = wp_generate_password(10);
		$user_id = wp_create_user( $first_name, $user_pass, $email_address ); // Create user
		update_post_meta($post_id, 'user-id', $user_id); // Update post meta
		update_user_meta($user_id, 'first-name', $first_name); // Update user meta
		update_user_meta($user_id, 'last-name', $last_name);
		update_user_meta($user_id, 'user-role', 'Client');
		$exist_user_id = $user_id;
		// Save Payment information
		if (isset($_POST['saveCardInfo'])) {
		  	if($_POST['hidden_payment_master_id']==''){ // payment information exist for this user 
			// Insert
				$result = $wpdb->insert( 
					$webapper->tables->user_payment_master, 
					array( 
					 'user_id'        			=> $exist_user_id,
					 'card_holder_name' 		=> $name_on_card,
					 'card_type'				=> $credit_card_type,
					 'card_number' 				=> $card_number,
					 'card_expiration_month' 	=> $cardExpirationMonth,
					 'card_expiration_year' 	=> $cardExpirationYear,
					 'card_country' 			=> $card_country,
					 'card_address' 			=> $card_address,
					 'card_city' 				=> $card_city,
					 'card_state' 				=> $card_state,
					 'card_ccv' 				=> $card_ccv,
					 'card_zip_code' 			=> $card_billing_zip,
					 'bank_routing_number' 		=> $bank_routing_number,
					 'bank_account_number' 		=> $bank_account_number,
					 'bank_check_number' 		=> $bank_check_number,	
					), 
					array( '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s','%s', '%s', '%s', '%s', '%s', '%s')
				);
				$this->user_payment_master_id = $wpdb->insert_id;
				
			}else{
				// Update 
				  $result = $wpdb->update( 
				$webapper->tables->user_payment_master, 
				array( 
					 'user_id'        			=> $exist_user_id,
					 'card_holder_name' 		=> $name_on_card,
					 'card_type'				=> $credit_card_type,
					 'card_number' 				=> $card_number,
					 'card_expiration_month' 	=> $cardExpirationMonth,
					 'card_expiration_year' 	=> $cardExpirationYear,
					 'card_country' 			=> $card_country,
					 'card_address' 			=> $card_address,
					 'card_city' 				=> $card_city,
					 'card_state' 				=> $card_state,
					 'card_ccv' 				=> $card_ccv,
					 'card_zip_code' 			=> $card_billing_zip,
					 'bank_routing_number' 		=> $bank_routing_number,
					 'bank_account_number' 		=> $bank_account_number,
					 'bank_check_number' 		=> $bank_check_number,	
					
				), 
				array( 'user_payment_master_id' =>  $user_payment_master_id ), 
				array( '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s','%s', '%s', '%s', '%s', '%s', '%s'), 
				array( '%d' ) 
			);	
			}
		}
		
	}
	       //  FETCHING VALUES FROM PAYMENT MASTER TABLE 
	        $payment_master = web_apper_get_payment_master($exist_user_id);
	        $user_payment_master_id = $payment_master ->user_payment_master_id;
			$card_holderName    	= $payment_master ->card_holder_name;
			$card_type         	    = $payment_master ->card_type;
			$card_number        	= $payment_master ->card_number;
			$cardExpire_month   	= $payment_master ->card_expiration_month;
			$cardExpire_year   	    = $payment_master ->card_expiration_year;
			$country            	= $payment_master ->card_country;
			$address            	= $payment_master ->card_address;
			$city               	= $payment_master ->card_city;
			$state              	= $payment_master ->card_state;
			$card_ccv           	= $payment_master ->card_ccv;
			$zip_code  				= $payment_master ->card_zip_code;
			$bank_routing_number	= $payment_master ->bank_routing_number;
			$account_number 		= $payment_master ->bank_account_number;
			$check_number 			= $payment_master ->bank_check_number;
?>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<div id="paymentMethods" style="display:none;">
  <div style="float:left">
    <div style="float:left">
    <h3>Debit/Credit Cards</h3>
    <form class="form-horizontal" action=""  method="post" name="debitCreditCards">
      <div class="control-group">
        <input type="hidden" name="hidden_payment_master_id" value="<?php echo $user_payment_master_id; ?>">
        <label class="control-label" for="Principal Amount">Name on Card:</label>
        <div class="controls">
          <input type="text" id="name_on_card" required name="name_on_card" placeholder="Card Holder Name" value="<?php echo $card_holderName ;?>">
        </div>
      </div>
      <div class="control-group">
        <label class="control-label" for="Credit Card Type">Credit Card Type</label>
        <div class="controls">
          <select name="credit_card_type" id="credit_card_type" class="selectpicker" data-live-search="true" data-size="5"  >
            <?php
				$creditCardTypeArray = array('Visa','MasterCard','American Express','Discover');
				foreach($creditCardTypeArray as $creditCard){
					if($creditCard == $card_type){
						echo "<option value=".$creditCard." selected>".$creditCard."</option>";
					}
					else
					{
						echo "<option value=".$creditCard.">".$creditCard."</option>";
					}
				}
			?>
          </select>
        </div>
      </div>
      <div class="control-group">
        <label class="control-label" for="Card Number">Card Number:</label>
        <div class="controls">
          <input type="text" id="card_number" required name="card_number" placeholder="Card Number" onchange="return CheckCreditCardNumber(this.value),validate(event);" onblur="return CheckCreditCardNumber(this.value),validate(event);"
 value="<?php echo $card_number ;?>"></br><span class="error_card_number" style="color: Red; display: none">Input digits (0 - 9) Only.</span>
        </div>
      </div>
      <div class="control-group">
        <label class="control-label" for="Card Expiration Date">Card Expiration Date:</label>
        <div class="controls">
          <select name="cardExpirationMonth" id="cardExpirationMonth" class="selectpicker" data-live-search="true" data-size="5" >
            <?php
				$monthArray =array('01','02','03','04','05','06','07','08','09','10','11','12'); 
				foreach($monthArray as $month){
					if($month == $cardExpire_month){
						echo "<option value=\"".$month."\" selected='selected'>".$month."</option>";
					}
					else{
						echo "<option value=\"".$month."\">".$month."</option>";
					}
				}
            ?>
          </select>
          <select name="cardExpirationYear"  id="cardExpirationYear" class="selectpicker" data-live-search="true" data-size="5" >
            <?php
			  $start_year = date('Y');
				$end_year = date('Y', strtotime($start_year .' +15 Year'));		
				$selected = is_null($selected) ? date('Y') : $selected;
				$r = range($start_year, $end_year);
				foreach( $r as $year ){
					if($cardExpire_year !=''){
						$select .= "<option value=\"$year\"";
						$select .= ($year ==$cardExpire_year) ? ' selected="selected"' : '';
						$select .= ">$year</option>\n";
					}
					else{
						$select .= "<option value=\"$year\"";
						$select .= ($year ==$selected) ? ' selected="selected"' : '';
						$select .= ">$year</option>\n";
					}
				}
				echo  $select;
				?>
          </select>
        </div>
      </div>
      <div class="control-group">
        <label class="control-label" for="Country">Country:</label>
        <div class="controls">
          <select name="card_country"  id="card_country" class="selectpicker" data-live-search="true" data-size="5" >
            <?php
		   $countrylist = web_apper_get_all_countries();
		        foreach($countrylist as $countryname => $countryshortname){
					if($countryshortname == $country ){
						echo "<option value=\"".$countryshortname."\" selected='selected'>".$countryname."</option>";
					}
					else{
						echo "<option value=\"".$countryshortname."\">".$countryname."</option>";
					}
				}
		   ?>
          </select>
        </div>
      </div>
      <div class="control-group">
        <label class="control-label" for="Address">Address:</label>
        <div class="controls">
          <textarea name="card_address" id="card_address" rows="3" cols="3"  > <?php echo $address; ?></textarea>
        </div>
      </div>
      <div class="control-group">
        <label class="control-label" for="City">City:</label>
        <div class="controls">
          <input type="text" id="card_city" required name="card_city" placeholder="City" value="<?php echo $city; ?>" >
        </div>
      </div>
      <div class="control-group">
        <label class="control-label" for="State">State:</label>
        <div class="controls">
          <input type="text" id="card_state" required name="card_state" placeholder="State"  value="<?php  echo  $state; ?>" >
        </div>
      </div>
      <div class="control-group">
        <label class="control-label" for="Card CCV">Card CCV:</label>
        <div class="controls">
          <input type="password" id="card_ccv" required name="card_ccv" placeholder="Card CCV" value="<?php echo $card_ccv ;?>" maxlength="5"></br><span class="error_card_ccv" style="color: Red; display: none">Input digits (0 - 9) Only.</span>
        </div>
      </div>
      <div class="control-group">
        <label class="control-label" for="Card Billing Zip">Card Billing Zip:</label>
        <div class="controls">
          <input type="text" id="card_billing_zip" required name="card_billing_zip" placeholder="Card Billing Zip"  onchange="return     CheckZipCode(this.value) " onblur=" return CheckZipCode(this.value)  " value="<?php echo $zip_code ;?>">
        </div>
      </div>
      <div class="control-group">
        <div class="controls">
          <button type="submit" class="btn btn-primary" name="saveCardInfo">Save</button>
        </div>
      </div>
      </div>
      <div  style="float:right; margin-left:100px">
      <h3>Electronic Checking</h3>
      <div class="form-horizontal" >
        <div class="control-group">
          <label class="control-label" for="Principal Amount">Bank Routing Number:</label>
          <div class="controls">
            <input type="text" id="bank_routing_number" required name="bank_routing_number" placeholder="Bank Routing Number" value="<?php echo $bank_routing_number;?>"></br><span class="error_bank_routing_number" style="color: Red; display: none">Input digits (0 - 9) Only.</span>
          </div>
        </div>
        <div class="control-group">
          <label class="control-label" for="Principal Amount">Account Number:</label>
          <div class="controls">
            <input type="text" id="bank_account_number" required name="bank_account_number" placeholder="Account Number" value="<?php echo $account_number ;?>"></br><span class="error_bank_account_number" style="color: Red; display: none">Input digits (0 - 9) Only.</span> 
          </div>
        </div>
        <div class="control-group">
          <label class="control-label" for="Check Number">Check Number:</label>
          <div class="controls">
            <input type="text" id="bank_check_number" required name="bank_check_number" placeholder="Check Number" value="<?php echo $check_number;?>"></br><span class="error_bank_check_number" style="color: Red; display: none">Input digits (0 - 9) Only.</span> 
          </div>
        </div>
      </div>
    </form>
  </div>
</div>
<div style="float:left">
  <h3 >Receive A Payment</h3>
  <form class="form-horizontal" action=""  method="post" name="receivePayment" >
    <div class="control-group">
      <label class="control-label" for="Principal Amount">Payment For:</label>
      <div class="controls">
        <select name="paymentFor" id="paymentFor" class="selectpicker" data-live-search="true" data-size="5">
          <option>Membershiop Expiration $45</option>
          <option>Loan Expiration $35</option>
        </select>
      </div>
    </div>
    <div class="control-group">
      <label class="control-label" for="Received As">Received As:</label>
      <div class="controls">
        <select name="receivedAs" class="selectpicker" id="receivedAs" data-live-search="true" data-size="5">
          <option>Cash</option>
        </select>
      </div>
    </div>
    <div class="control-group">
      <label class="control-label" for="Principal Amount">Amount ($):</label>
      <div class="controls">
        <input type="text" id="amount" required name="amount" placeholder="Amount" value="<?php echo $amount;?>" >
      </div>
    </div>
    <div class="control-group">
      <div class="controls">
        <button type="submit" class="btn btn-primary" name="saveReceivePayment">Save</button>
      </div>
    </div>
  </form>
</div>
</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
	$('.selectpicker').selectpicker();
	  
});
var specialKeys = new Array();
specialKeys.push(8); //Backspace
        
		 $(function () {
			$("#card_number").bind("keypress", function (e) {
				var keyCode = e.which ? e.which : e.keyCode
				var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
				$(".error_card_number").css("display", ret ? "none" : "inline").fadeOut("slow");
				return ret;
			});
 	    });
		
		$(function () {
			$("#card_ccv").bind("keypress", function (e) {
				var keyCode = e.which ? e.which : e.keyCode
				var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
				$(".error_card_ccv").css("display", ret ? "none" : "inline").fadeOut("slow");
				return ret;
			});
 	    });
		
		$(function () {
			$("#bank_routing_number").bind("keypress", function (e) {
				var keyCode = e.which ? e.which : e.keyCode
				var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
				$(".error_bank_routing_number").css("display", ret ? "none" : "inline").fadeOut("slow");
				return ret;
			});
		});
		
		$(function () {
			$("#bank_account_number").bind("keypress", function (e) {
				var keyCode = e.which ? e.which : e.keyCode
				var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
				$(".error_bank_account_number").css("display", ret ? "none" : "inline").fadeOut("slow");
				return ret;
			});
		 });
	
	   $(function () {
			$("#bank_check_number").bind("keypress", function (e) {
				var keyCode = e.which ? e.which : e.keyCode
				var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
				$(".error_bank_check_number").css("display", ret ? "none" : "inline").fadeOut("slow");
				return ret;
			});
 	    });
		
		
function CheckZipCode(strString) 
{
	var strValidChars = "0123456789";
	var strChar;
	var blnResult = true;
	if (strString.length == 0) return false;
// test strString consists of valid characters listed above
	for (i = 0; i < strString.length && blnResult == true; i++)
	{
		strChar = strString.charAt(i);
		if (strValidChars.indexOf(strChar) == -1)
		{
			alert("Please type in correct zipcode format.");
		    document.getElementById('txtZipCode').value='';
		    document.getElementById('txtZipCode').focus();
			blnResult = false;
		}
	}
	return blnResult;
}

function CheckCreditCardNumber(strString)
{
	var reCreditCard = /[\.\,\?!\s]/g;
	var strValidChars = "0123456789";
	var strChar;
	var blnResult = true;
	if (strString.length != 16)
	{
		alert('You entered an invalid credit card number. Please try again.');
		document.getElementById('txtCreditCardNumber').value='';
		document.getElementById('txtCreditCardNumber').focus();
		return false;
	}
	if(reCreditCard.test(strString))
	{
		alert("Numeric characters only with no spaces or punctutation.");
		document.getElementById('txtCreditCardNumber').value='';
		document.getElementById('txtCreditCardNumber').focus();
		return false;
	}
	
	var sum = 0; 
	var numdigits = strString.length; 
	var parity = numdigits % 2; 
	for(var i=0; i < numdigits; i++)
	{ 
		var digit = parseInt(strString.charAt(i)) 
		if(i % 2 == parity)
		digit *= 2; 
		if(digit > 9) 
		digit -= 9;
		sum += digit;
	}
	if((sum % 10) != 0)
	{
		alert('You entered an invalid credit card number. Please try again.');
		document.getElementById('txtCreditCardNumber').value='';
		document.getElementById('txtCreditCardNumber').focus();
		return false;
	}
// test strString consists of valid characters listed above
	for (i = 0; i < strString.length && blnResult == true; i++)
	{
		strChar = strString.charAt(i);
		if (strValidChars.indexOf(strChar) == -1)
		{
			alert("Numeric characters only with no spaces or punctutation.");
		    document.getElementById('txtCreditCardNumber').value='';
		    document.getElementById('txtCreditCardNumber').focus();
			blnResult = false;
		}
	}
	return blnResult;
}

function validate(event) {
 var key = window.event ? event.keyCode : event.which;

    if (event.keyCode == 8 || event.keyCode == 46
     || event.keyCode == 37 || event.keyCode == 39) {
        return true;
    }
   var theEvent = event || window.event;
  var key = theEvent.keyCode || theEvent.which;
  key = String.fromCharCode( key );
  var regex = /[0-9]|\./;
  if( !regex.test(key) ) {
    theEvent.returnValue = false;
    if(theEvent.preventDefault) theEvent.preventDefault();
  }
}

</script>
<?php	}		
}
$initialize = new PaymentMethods(); 

?>
